package com.seashop.exception;

import com.seashop.response.ResponseBase;
import com.seashop.constant.BaseConstant;
import com.seashop.enums.ResponseEnum;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author moredln
 * @desc
 * @date 2020-09-08 16:25
 */
@ControllerAdvice
@ResponseBody
public class ExceptionHandlerAdvice {

    @ExceptionHandler
    public ResponseBase exceptionHandler(MethodArgumentNotValidException e) {
        Map<String, String> collect = e.getBindingResult().getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return ResponseBase.fail(ResponseEnum.SERVER_ERROR.getCode(), ResponseEnum.SERVER_ERROR.getMsg(), collect);
    }

    @ExceptionHandler
    public ResponseBase exceptionHandler(MissingServletRequestParameterException e) {
        return ResponseBase.fail(BaseConstant.MISS_FIELD + e.getParameterName());
    }

    @ExceptionHandler
    public ResponseBase exceptionHandler(ConstraintViolationException e) {
        return ResponseBase.fail(e.getMessage());
    }
}
